package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Yandel
 * @since 2025-07-03
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryShopById(Long id) {
        //缓存穿透
//        Shop shop = queryWithPassThrough(id);

        //互斥锁
//        Shop shop = queryWithMutex(id);

        //使用逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicExpire(id);
//        Shop shop = cacheClient.queryWithLogicalExpire
//                (CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY,
                id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //注意：这里为什么要判断，因为shopJson可能为""
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        //6、返回
        return Result.ok(shop);
    }

    /**
     * 编写逻辑过期解决缓存击穿
     *
     * @param id
     * @param expireSeconds
     */
    public void saveShop2Redis(Long id, Long expireSeconds) {
        //1.查询店铺
        Shop shop = this.getById(id);

        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));//现在时间加上过期时间

        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 使用互斥锁实现缓存击穿
     *
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id; //cache:shop:id
        //1、从Redis中查询商铺缓存数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {//不是空——拿到数据
            //存在，直接返回数据
            //将json数据转为对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        //判断名中的是否是空值
        if (shopJson != null) {//在做缓存穿透时设置的key为空 ""，但是空不会等于null
            //存在空值key，返回错误
            return null;
        }

        //4、未命中，实现缓存重建
        //4.1、获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //4.2、判断是否获取成功
            if (!isLock) {
                //4.3、失败，则休眠重试
                Thread.sleep(50);
                //递归调用
                return queryWithMutex(id);
            }

            //4.4、成功，根据id查询数据库
            shop = this.getById(id);
            //5、不存在，返回错误
            if (shop == null) {

                //将空值写入redis  cache:shop:0  value为空
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

                //数据库不存在，返回错误
                return null;
            }
            //6、存在，写入Redis      //将对象转为json字符串
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7、释放互斥锁
            unLock(lockKey);
        }

        //8、返回
        return shop;
    }


    /**
     * 使用逻辑过期时间解决缓存击穿
     * 注意：是为了解决热点数据问题（所以前提数据库是会有数据的）
     */
    public Shop queryWithLogicExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id; //cache:shop:id
        //1、从Redis中查询商铺缓存数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isBlank(shopJson)) {//是空
            return null;
        }
        //3、命中，需要把JSON反序列化得到对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        //过期时间
        LocalDateTime expireTime = redisData.getExpireTime();

        //4、判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期，直接返回数据
            return shop;
        }

        //5、过期，需要缓存重建
        //6、缓存重建
        //6.1、获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2、判断锁是否获取成功
        if (isLock) {
            //6.2.1、 成功，开启独立线程，实现缓存重建
        }
        //6.3、成功，开启独立线程，实现缓存重建
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                this.saveShop2Redis(id, 20L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                unLock(lockKey);
            }
        });

        //6.4、返回过期的商铺信息
        return shop;
    }
    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public Shop queryWithPassThrough(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id; //cache:shop:id
        //1、从Redis中查询商铺缓存数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {//不是空
            //存在，直接返回数据
            //将json数据转为对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断名中的是否是空值
        if (shopJson != null) {
            //存在，返回错误
            return null;
        }

        //4、不存在，返回错误，并查询数据库
        Shop shop = this.getById(id);
        if (shop == null) {

            //将空值写入redis  cache:shop:0  value为空
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);

            //数据库不存在，返回错误
            return null;
        }
        //5、存在，写入Redis      //将对象转为json字符串
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //6、返回
        return shop;
    }

    /**
     * 基于互斥锁实现解决缓存击穿问题
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//BooleanUtil自动检查 flag，是true还是false
    }

    /**
     * 释放锁
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok("更新成功~");
    }


    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = this.query()
                    .eq("type_id", typeId)
                    //页码          默认分页大小
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results =
                stringRedisTemplate.opsForGeo().search(
                        key,// 查询的key
                        GeoReference.fromCoordinate(x, y),// 坐标
                        new Distance(5000),// 距离 5km
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

/*        Circle circle = new Circle(new Point(x, y), new Distance(5000, Metrics.KILOMETERS));
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()
                .limit(end);

        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .radius(key, circle, args);*/

        log.info("从Redis中查询到的results: {}", results);
        // 4.解析出id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
//        log.info("从Redis中查询到的list: {}", list);

        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>(list.size());

        log.info("获取到的distanceMap值为：{}", distanceMap);
        list.stream().skip(from).forEach(result -> {//跳过from前面几页
            //4.2、获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3、获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        log.info("过滤之后的元素：{}", list);
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = this.query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
}
